package com.property.demo.controller;

import com.property.demo.dto.ApiResponse;
import com.property.demo.model.*;
import com.property.demo.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.Calendar;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Random;
import org.springframework.http.HttpStatus;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/init")
public class DataInitController {

    private static final Logger logger = LoggerFactory.getLogger(DataInitController.class);
    private final Random random = new Random();

    @Autowired
    private DataSource dataSource;

    @Autowired
    private ParkingRepository parkingRepository;
    
    @Autowired
    private OwnerRepository ownerRepository;
    
    @Autowired
    private VehicleRepository vehicleRepository;
    
    @Autowired
    private ParkingUsageRepository parkingUsageRepository;
    
    @Autowired
    private CommunityRepository communityRepository;
    
    @Autowired
    private BuildingRepository buildingRepository;
    
    @Autowired
    private HomeRepository homeRepository;
    
    @Autowired
    private ComplaintRepository complaintRepository;
    
    @Autowired
    private RepairRepository repairRepository;
    
    @Autowired
    private ActivityRepository activityRepository;
    
    @Autowired
    private MailboxRepository mailboxRepository;

    @GetMapping
    public ResponseEntity<String> initDatabase() throws IOException {
        try {
            // 使用SQL脚本初始化数据
            ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
            // 执行数据库初始化
            populator.execute(dataSource);
            return ResponseEntity.ok("数据库初始化成功");
        } catch (Exception e) {
            return ResponseEntity.status(500).body("数据库初始化失败: " + e.getMessage());
        }
    }
    
    /**
     * 初始化社区数据
     */
    private List<Community> initCommunityData() {
        logger.info("初始化社区数据");
        
        // 创建示例社区数据
        List<Community> communities = new ArrayList<>();
        
        Community community1 = new Community();
        community1.setName("阳光花园");
        community1.setAddress("北京市朝阳区阳光路123号");
        community1.setArea(50000.0);
        community1.setTotalBuildings(10);
        community1.setTotalHomes(500);
        community1.setDeveloperName("阳光地产");
        community1.setPropertyCompany("阳光物业");
        communities.add(community1);
        
        Community community2 = new Community();
        community2.setName("和平公寓");
        community2.setAddress("北京市海淀区和平路456号");
        community2.setArea(30000.0);
        community2.setTotalBuildings(5);
        community2.setTotalHomes(300);
        community2.setDeveloperName("和平地产");
        community2.setPropertyCompany("和平物业");
        communities.add(community2);
        
        Community community3 = new Community();
        community3.setName("翠湖山庄");
        community3.setAddress("北京市丰台区翠湖路789号");
        community3.setArea(100000.0);
        community3.setTotalBuildings(20);
        community3.setTotalHomes(100);
        community3.setDeveloperName("翠湖地产");
        community3.setPropertyCompany("翠湖物业");
        communities.add(community3);
        
        return communityRepository.saveAll(communities);
    }
    
    /**
     * 初始化业主数据
     */
    private List<Owner> initOwnerData() {
        logger.info("初始化业主数据");
        
        // 创建示例业主数据
        List<Owner> owners = new ArrayList<>();
        
        Owner owner1 = new Owner();
        owner1.setName("张三");
        owner1.setGender("男");
        owner1.setPhoneNumber("13800138001");
        owner1.setEmail("zhangsan@example.com");
        owner1.setIdCard("110101198001010001");
        owners.add(owner1);
        
        Owner owner2 = new Owner();
        owner2.setName("李四");
        owner2.setGender("男");
        owner2.setPhoneNumber("13800138002");
        owner2.setEmail("lisi@example.com");
        owner2.setIdCard("110101198201010002");
        owners.add(owner2);
        
        Owner owner3 = new Owner();
        owner3.setName("王五");
        owner3.setGender("女");
        owner3.setPhoneNumber("13800138003");
        owner3.setEmail("wangwu@example.com");
        owner3.setIdCard("110101198301010003");
        owners.add(owner3);
        
        return ownerRepository.saveAll(owners);
    }
    
    /**
     * 初始化车位数据
     */
    private List<Parking> initParkingData() {
        logger.info("初始化车位数据");
        
        // 获取或创建社区
        List<Community> communities = communityRepository.findAll();
        if (communities.isEmpty()) {
            communities = initCommunityData();
        }
        
        // 创建示例车位数据
        List<Parking> parkings = new ArrayList<>();
        
        Parking parking1 = new Parking();
        parking1.setName("A-001");
        parking1.setCommunity(communities.get(0));
        parking1.setType("地下");
        parking1.setStatus("空闲");
        parking1.setArea(12.5);
        parking1.setPrice(200.0);
        parkings.add(parking1);
        
        Parking parking2 = new Parking();
        parking2.setName("B-002");
        parking2.setCommunity(communities.size() > 1 ? communities.get(1) : communities.get(0));
        parking2.setType("地上");
        parking2.setStatus("空闲");
        parking2.setArea(15.0);
        parking2.setPrice(300.0);
        parkings.add(parking2);
        
        Parking parking3 = new Parking();
        parking3.setName("C-003");
        parking3.setCommunity(communities.size() > 2 ? communities.get(2) : communities.get(0));
        parking3.setType("地下");
        parking3.setStatus("空闲");
        parking3.setArea(13.0);
        parking3.setPrice(250.0);
        parkings.add(parking3);
        
        return parkingRepository.saveAll(parkings);
    }
    
    /**
     * 初始化车辆数据
     */
    private List<Vehicle> initVehicleData() {
        logger.info("初始化车辆数据");
        
        // 获取或创建业主
        List<Owner> owners = ownerRepository.findAll();
        if (owners.isEmpty()) {
            owners = initOwnerData();
        }
        
        // 创建示例车辆数据
        List<Vehicle> vehicles = new ArrayList<>();
        
        Vehicle vehicle1 = new Vehicle();
        vehicle1.setLicensePlate("京A12345");
        vehicle1.setOwner(owners.get(0));
        vehicle1.setBrand("丰田");
        vehicle1.setModel("Camry");
        vehicle1.setColor("白色");
        vehicle1.setType("轿车");
        vehicle1.setParkingLocation("A区-001");
        vehicle1.setParkingPermitNumber("P20230001");
        Calendar calendar1 = Calendar.getInstance();
        calendar1.add(Calendar.YEAR, 1);
        vehicle1.setPermitExpiryDate(calendar1.getTime());
        vehicle1.setStatus("正常");
        vehicle1.setRemarks("业主日常用车");
        vehicles.add(vehicle1);
        
        if (owners.size() > 1) {
            Vehicle vehicle2 = new Vehicle();
            vehicle2.setLicensePlate("京B54321");
            vehicle2.setOwner(owners.get(1));
            vehicle2.setBrand("本田");
            vehicle2.setModel("CR-V");
            vehicle2.setColor("黑色");
            vehicle2.setType("SUV");
            vehicle2.setParkingLocation("B区-002");
            vehicle2.setParkingPermitNumber("P20230002");
            Calendar calendar2 = Calendar.getInstance();
            calendar2.add(Calendar.MONTH, 11);
            vehicle2.setPermitExpiryDate(calendar2.getTime());
            vehicle2.setStatus("正常");
            vehicle2.setRemarks("家用车");
            vehicles.add(vehicle2);
        }
        
        if (owners.size() > 2) {
            Vehicle vehicle3 = new Vehicle();
            vehicle3.setLicensePlate("京C98765");
            vehicle3.setOwner(owners.get(2));
            vehicle3.setBrand("大众");
            vehicle3.setModel("Passat");
            vehicle3.setColor("银色");
            vehicle3.setType("轿车");
            vehicle3.setParkingLocation("C区-003");
            vehicle3.setParkingPermitNumber("P20230003");
            Calendar calendar3 = Calendar.getInstance();
            calendar3.add(Calendar.MONTH, 10);
            vehicle3.setPermitExpiryDate(calendar3.getTime());
            vehicle3.setStatus("正常");
            vehicle3.setRemarks("工作用车");
            vehicles.add(vehicle3);
        }
        
        return vehicleRepository.saveAll(vehicles);
    }

    /**
     * 初始化车位使用记录测试数据
     */
    @PostMapping("/parking-usages")
    public ResponseEntity<?> initParkingUsageData() {
        try {
            logger.info("开始初始化车位使用记录测试数据");
            
            // 清空现有数据
            parkingUsageRepository.deleteAll();
            
            // 确保有车位数据
            if (parkingRepository.count() == 0) {
                initParkingData();
            }
            
            // 确保有业主数据
            if (ownerRepository.count() == 0) {
                initOwnerData();
            }
            
            // 确保有车辆数据
            if (vehicleRepository.count() == 0) {
                initVehicleData();
            }
            
            // 获取所有车位
            List<Parking> parkings = parkingRepository.findAll();
            if (parkings.isEmpty()) {
                return ResponseEntity.badRequest().body("没有车位数据，无法初始化车位使用记录");
            }
            
            // 获取所有业主
            List<Owner> owners = ownerRepository.findAll();
            if (owners.isEmpty()) {
                return ResponseEntity.badRequest().body("没有业主数据，无法初始化车位使用记录");
            }
            
            // 获取所有车辆
            List<Vehicle> vehicles = vehicleRepository.findAll();
            
            // 创建测试数据
            List<ParkingUsage> parkingUsages = new ArrayList<>();
            
            // 示例1：业主1购买车位1
            ParkingUsage pu1 = new ParkingUsage();
            pu1.setParking(parkings.get(0));
            pu1.setOwner(owners.get(0));
            if (!vehicles.isEmpty()) {
                pu1.setVehicle(vehicles.get(0));
            }
            pu1.setUsageType(2); // "购买" -> 2
            pu1.setStartDate(new Date());
            Calendar endCal = Calendar.getInstance();
            endCal.add(Calendar.YEAR, 1);
            pu1.setEndDate(endCal.getTime());
            pu1.setFee(2400.0);
            pu1.setPaymentStatus("已支付");
            pu1.setRemarks("年付车位使用费");
            parkingUsages.add(pu1);
            
            // 示例2：业主2租用车位2
            if (parkings.size() > 1 && owners.size() > 1) {
                ParkingUsage pu2 = new ParkingUsage();
                pu2.setParking(parkings.get(1));
                pu2.setOwner(owners.get(1));
                if (vehicles.size() > 1) {
                    pu2.setVehicle(vehicles.get(1));
                }
                pu2.setUsageType(1); // "租用" -> 1
                pu2.setStartDate(new Date());
                Calendar endCal2 = Calendar.getInstance();
                endCal2.add(Calendar.MONTH, 3);
                pu2.setEndDate(endCal2.getTime());
                pu2.setFee(900.0);
                pu2.setPaymentStatus("已支付");
                pu2.setRemarks("季度租用");
                parkingUsages.add(pu2);
            }
            
            // 示例3：业主3购买车位3
            if (parkings.size() > 2 && owners.size() > 2) {
                ParkingUsage pu3 = new ParkingUsage();
                pu3.setParking(parkings.get(2));
                pu3.setOwner(owners.get(2));
                if (vehicles.size() > 2) {
                    pu3.setVehicle(vehicles.get(2));
                }
                pu3.setUsageType(2); // "购买" -> 2
                pu3.setStartDate(new Date());
                Calendar endCal3 = Calendar.getInstance();
                endCal3.add(Calendar.YEAR, 1);
                pu3.setEndDate(endCal3.getTime());
                pu3.setFee(3000.0);
                pu3.setPaymentStatus("部分支付");
                pu3.setRemarks("分期支付");
                parkingUsages.add(pu3);
            }
            
            // 保存测试数据
            List<ParkingUsage> savedParkingUsages = parkingUsageRepository.saveAll(parkingUsages);
            logger.info("成功初始化车位使用记录测试数据，共 {} 条记录", savedParkingUsages.size());
            
            Map<String, Object> response = new HashMap<>();
            response.put("message", "成功初始化车位使用记录测试数据");
            response.put("count", savedParkingUsages.size());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("初始化车位使用记录测试数据失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("初始化车位使用记录测试数据失败: " + e.getMessage());
        }
    }

    /**
     * 生成大量测试数据
     */
    @PostMapping("/generate-bulk-data")
    public ResponseEntity<?> generateBulkData() {
        try {
            // 生成50条社区数据
            List<Community> communities = generateCommunities(50);
            
            // 生成50条业主数据
            List<Owner> owners = generateOwners(50);
            
            // 为每个社区生成若干楼宇数据，总计至少50条
            List<Building> buildings = generateBuildings(communities, 50);
            
            // 为每个楼宇生成若干房屋数据，总计至少50条
            List<Home> homes = generateHomes(buildings, owners, 50);
            
            // 生成50条车位数据，分布在不同社区
            List<Parking> parkings = generateParkings(communities, 50);
            
            // 生成50条车辆数据，关联到业主
            List<Vehicle> vehicles = generateVehicles(owners, 50);
            
            // 生成50条车位使用记录，关联车位、业主和车辆
            List<ParkingUsage> parkingUsages = generateParkingUsages(parkings, owners, vehicles, 50);
            
            // 生成50条投诉数据
            List<Complaint> complaints = generateComplaints(owners, 50);
            
            // 生成50条报修数据
            List<Repair> repairs = generateRepairs(owners, homes, 50);
            
            // 生成50条活动数据
            List<Activity> activities = generateActivities(communities, 50);
            
            // 生成50条信箱数据
            List<Mailbox> mailboxes = generateMailboxes(owners, 50);
            
            Map<String, Object> response = new HashMap<>();
            response.put("message", "成功生成批量测试数据");
            response.put("communities", communities.size());
            response.put("owners", owners.size());
            response.put("buildings", buildings.size());
            response.put("homes", homes.size());
            response.put("parkings", parkings.size());
            response.put("vehicles", vehicles.size());
            response.put("parkingUsages", parkingUsages.size());
            response.put("complaints", complaints.size());
            response.put("repairs", repairs.size());
            response.put("activities", activities.size());
            response.put("mailboxes", mailboxes.size());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("生成批量测试数据失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("生成批量测试数据失败: " + e.getMessage());
        }
    }
    
    /**
     * 生成社区数据
     */
    private List<Community> generateCommunities(int count) {
        logger.info("开始生成{}条社区数据", count);
        List<Community> communities = new ArrayList<>();
        String[] cityPrefixes = {"北京", "上海", "广州", "深圳", "杭州", "南京", "成都", "重庆", "武汉", "西安"};
        String[] communityTypes = {"花园", "公寓", "小区", "山庄", "家园", "广场", "城邦", "御园", "名邸", "豪庭"};
        String[] developerPrefixes = {"恒大", "万科", "碧桂园", "保利", "绿城", "华润", "龙湖", "金地", "融创", "招商"};
        
        for (int i = 0; i < count; i++) {
            Community community = new Community();
            String cityPrefix = cityPrefixes[i % cityPrefixes.length];
            String communityType = communityTypes[i % communityTypes.length];
            String developerPrefix = developerPrefixes[i % developerPrefixes.length];
            
            community.setName(cityPrefix + (i + 1) + communityType);
            community.setAddress(cityPrefix + "市" + (i % 10 + 1) + "区" + (i % 100 + 1) + "号");
            community.setArea(10000.0 + i * 1000);
            community.setTotalBuildings(5 + i % 10);
            community.setTotalHomes(100 + i * 10);
            community.setDeveloperName(developerPrefix + "地产");
            community.setPropertyCompany(developerPrefix + "物业");
            community.setCreatedAt(new Date());
            community.setUpdatedAt(new Date());
            
            communities.add(community);
        }
        
        List<Community> savedCommunities = communityRepository.saveAll(communities);
        logger.info("成功生成{}条社区数据", savedCommunities.size());
        return savedCommunities;
    }
    
    /**
     * 生成业主数据
     */
    private List<Owner> generateOwners(int count) {
        logger.info("开始生成{}条业主数据", count);
        List<Owner> owners = new ArrayList<>();
        
        // 姓氏
        String[] lastNames = {"张", "王", "李", "赵", "陈", "刘", "杨", "黄", "周", "吴", 
                             "郑", "孙", "马", "朱", "胡", "林", "郭", "何", "高", "罗"};
        
        // 名字常用字
        String[] firstNames = {"伟", "芳", "娜", "秀英", "敏", "静", "丽", "强", "磊", "军", 
                              "洋", "勇", "艳", "杰", "娟", "涛", "明", "超", "秀兰", "霞"};
        
        // 邮箱后缀
        String[] emailSuffixes = {"@qq.com", "@163.com", "@gmail.com", "@hotmail.com", "@yahoo.com",
                                 "@sina.com", "@126.com", "@outlook.com", "@foxmail.com", "@sohu.com"};
        
        // 性别
        String[] genders = {"男", "女"};
        
        for (int i = 0; i < count; i++) {
            Owner owner = new Owner();
            
            // 随机生成姓名
            String lastName = lastNames[random.nextInt(lastNames.length)];
            String firstName = firstNames[random.nextInt(firstNames.length)];
            String fullName = lastName + firstName;
            
            // 随机生成性别
            String gender = genders[random.nextInt(genders.length)];
            
            // 随机生成手机号
            String phone = "1" + (random.nextInt(3) + 3) + generateRandomDigits(9);
            
            // 随机生成邮箱
            String email = pinyin(lastName) + pinyin(firstName) + (i + 1) + 
                           emailSuffixes[random.nextInt(emailSuffixes.length)];
            
            // 随机生成身份证号
            String idCard = generateRandomIdCard();
            
            owner.setName(fullName);
            owner.setGender(gender);
            owner.setPhoneNumber(phone);
            owner.setEmail(email);
            owner.setIdCard(idCard);
            owner.setCreatedAt(new Date());
            owner.setUpdatedAt(new Date());
            
            owners.add(owner);
        }
        
        List<Owner> savedOwners = ownerRepository.saveAll(owners);
        logger.info("成功生成{}条业主数据", savedOwners.size());
        return savedOwners;
    }
    
    /**
     * 生成指定长度的随机数字字符串
     */
    private String generateRandomDigits(int length) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }
    
    /**
     * 简单的拼音转换，仅用于示例
     */
    private String pinyin(String chinese) {
        // 这里简化处理，实际应用中可以使用拼音转换库
        Map<String, String> pinyinMap = new HashMap<>();
        pinyinMap.put("张", "zhang");
        pinyinMap.put("王", "wang");
        pinyinMap.put("李", "li");
        pinyinMap.put("赵", "zhao");
        pinyinMap.put("陈", "chen");
        pinyinMap.put("刘", "liu");
        pinyinMap.put("杨", "yang");
        pinyinMap.put("黄", "huang");
        pinyinMap.put("周", "zhou");
        pinyinMap.put("吴", "wu");
        pinyinMap.put("郑", "zheng");
        pinyinMap.put("孙", "sun");
        pinyinMap.put("马", "ma");
        pinyinMap.put("朱", "zhu");
        pinyinMap.put("胡", "hu");
        pinyinMap.put("林", "lin");
        pinyinMap.put("郭", "guo");
        pinyinMap.put("何", "he");
        pinyinMap.put("高", "gao");
        pinyinMap.put("罗", "luo");
        pinyinMap.put("伟", "wei");
        pinyinMap.put("芳", "fang");
        pinyinMap.put("娜", "na");
        pinyinMap.put("秀英", "xiuying");
        pinyinMap.put("敏", "min");
        pinyinMap.put("静", "jing");
        pinyinMap.put("丽", "li");
        pinyinMap.put("强", "qiang");
        pinyinMap.put("磊", "lei");
        pinyinMap.put("军", "jun");
        pinyinMap.put("洋", "yang");
        pinyinMap.put("勇", "yong");
        pinyinMap.put("艳", "yan");
        pinyinMap.put("杰", "jie");
        pinyinMap.put("娟", "juan");
        pinyinMap.put("涛", "tao");
        pinyinMap.put("明", "ming");
        pinyinMap.put("超", "chao");
        pinyinMap.put("秀兰", "xiulan");
        pinyinMap.put("霞", "xia");
        
        return pinyinMap.getOrDefault(chinese, "unknown");
    }
    
    /**
     * 生成随机身份证号
     */
    private String generateRandomIdCard() {
        // 简化处理，实际应用中需要更复杂的逻辑
        String[] areaCodes = {"110101", "310101", "440101", "440301", "330101", "320101", "510101", "500101", "420101", "610101"};
        String areaCode = areaCodes[random.nextInt(areaCodes.length)];
        
        // 生成出生日期：1960-01-01到2000-12-31
        Calendar cal = Calendar.getInstance();
        cal.set(1960, 0, 1);
        long start = cal.getTimeInMillis();
        cal.set(2000, 11, 31);
        long end = cal.getTimeInMillis();
        long randomTimestamp = start + (long) (random.nextDouble() * (end - start));
        cal.setTimeInMillis(randomTimestamp);
        
        String year = String.format("%04d", cal.get(Calendar.YEAR));
        String month = String.format("%02d", cal.get(Calendar.MONTH) + 1);
        String day = String.format("%02d", cal.get(Calendar.DAY_OF_MONTH));
        
        String birthDate = year + month + day;
        
        // 生成顺序码
        String sequenceCode = String.format("%03d", random.nextInt(1000));
        
        // 简化处理，不计算校验码
        String checkCode = String.valueOf(random.nextInt(10));
        
        return areaCode + birthDate + sequenceCode + checkCode;
    }
    
    /**
     * 生成楼宇数据
     */
    private List<Building> generateBuildings(List<Community> communities, int count) {
        logger.info("开始生成{}条楼宇数据", count);
        List<Building> buildings = new ArrayList<>();
        
        // 楼宇名称前缀
        String[] buildingPrefixes = {"A", "B", "C", "D", "E", "F", "G", "H", "J", "K"};
        
        // 楼宇类型
        String[] buildingTypes = {"高层", "小高层", "多层", "别墅", "洋房"};
        
        int buildingsPerCommunity = count / communities.size() + 1;
        
        for (Community community : communities) {
            for (int i = 0; i < buildingsPerCommunity && buildings.size() < count; i++) {
                Building building = new Building();
                
                String buildingPrefix = buildingPrefixes[i % buildingPrefixes.length];
                String buildingType = buildingTypes[random.nextInt(buildingTypes.length)];
                
                building.setName(buildingPrefix + "栋");
                building.setCommunity(community);
                building.setTotalFloors(5 + random.nextInt(25)); // 5-30层
                building.setTotalUnits(1 + random.nextInt(4)); // 1-4个单元
                building.setDescription(buildingType);
                building.setCreatedAt(new Date());
                building.setUpdatedAt(new Date());
                
                buildings.add(building);
            }
        }
        
        List<Building> savedBuildings = buildingRepository.saveAll(buildings);
        logger.info("成功生成{}条楼宇数据", savedBuildings.size());
        return savedBuildings;
    }
    
    /**
     * 生成房屋数据
     */
    private List<Home> generateHomes(List<Building> buildings, List<Owner> owners, int count) {
        logger.info("开始生成{}条房屋数据", count);
        List<Home> homes = new ArrayList<>();
        
        // 房屋类型
        String[] homeTypes = {"一室一厅", "两室一厅", "两室两厅", "三室一厅", "三室两厅", "四室两厅", "复式", "跃层", "LOFT"};
        
        // 房屋状态
        String[] homeStatus = {"已售", "待售", "已租", "空置"};
        
        int homesPerBuilding = count / buildings.size() + 1;
        
        for (Building building : buildings) {
            for (int floor = 1; floor <= building.getTotalFloors() && homes.size() < count; floor++) {
                for (int unit = 1; unit <= building.getTotalUnits() && homes.size() < count; unit++) {
                    for (int room = 1; room <= 4 && homes.size() < count; room++) {
                        if (homes.size() >= homesPerBuilding * (buildings.indexOf(building) + 1)) {
                            break;
                        }
                        
                        Home home = new Home();
                        
                        String roomNumber = String.format("%02d%02d", floor, room);
                        String homeType = homeTypes[random.nextInt(homeTypes.length)];
                        String status = homeStatus[random.nextInt(homeStatus.length)];
                        
                        home.setBuilding(building);
                        home.setName(unit + "单元" + roomNumber);
                        home.setFloor(floor);
                        home.setArea(60.0 + random.nextInt(140)); // 60-200平方米
                        home.setType(homeType);
                        home.setStatus(status);
                        
                        // 如果房屋已售，则随机分配一个业主
                        if ("已售".equals(status) && !owners.isEmpty()) {
                            home.setOwner(owners.get(random.nextInt(owners.size())));
                        }
                        
                        home.setCreatedAt(new Date());
                        home.setUpdatedAt(new Date());
                        
                        homes.add(home);
                    }
                }
            }
        }
        
        List<Home> savedHomes = homeRepository.saveAll(homes);
        logger.info("成功生成{}条房屋数据", savedHomes.size());
        return savedHomes;
    }
    
    /**
     * 生成车位数据
     */
    private List<Parking> generateParkings(List<Community> communities, int count) {
        logger.info("开始生成{}条车位数据", count);
        List<Parking> parkings = new ArrayList<>();
        
        // 车位类型
        String[] parkingTypes = {"地上", "地下", "露天"};
        
        // 车位状态
        String[] parkingStatus = {"空闲", "已使用", "维修中", "预留"};
        
        // 车位区域
        String[] parkingAreas = {"A", "B", "C", "D", "E", "F", "G", "H"};
        
        int parkingsPerCommunity = count / communities.size() + 1;
        
        for (Community community : communities) {
            for (int i = 0; i < parkingsPerCommunity && parkings.size() < count; i++) {
                Parking parking = new Parking();
                
                String parkingArea = parkingAreas[i / 100 % parkingAreas.length];
                String parkingNumber = String.format("%03d", i % 100 + 1);
                String parkingType = parkingTypes[random.nextInt(parkingTypes.length)];
                String status = parkingStatus[random.nextInt(parkingStatus.length)];
                
                parking.setName(parkingArea + "-" + parkingNumber);
                parking.setCommunity(community);
                parking.setType(parkingType);
                parking.setStatus(status);
                parking.setArea(12.0 + random.nextDouble() * 6.0); // 12-18平方米
                parking.setPrice(200.0 + random.nextDouble() * 300.0); // 200-500元/月
                parking.setCreatedAt(new Date());
                parking.setUpdatedAt(new Date());
                
                parkings.add(parking);
            }
        }
        
        List<Parking> savedParkings = parkingRepository.saveAll(parkings);
        logger.info("成功生成{}条车位数据", savedParkings.size());
        return savedParkings;
    }
    
    /**
     * 生成车辆数据
     */
    private List<Vehicle> generateVehicles(List<Owner> owners, int count) {
        logger.info("开始生成{}条车辆数据", count);
        List<Vehicle> vehicles = new ArrayList<>();
        
        // 汽车品牌
        String[] brands = {"大众", "丰田", "本田", "日产", "福特", "别克", "宝马", "奔驰", "奥迪", "现代",
                          "起亚", "雪佛兰", "马自达", "斯柯达", "沃尔沃", "雷克萨斯", "凯迪拉克", "路虎", "特斯拉", "比亚迪"};
        
        // 汽车型号
        Map<String, String[]> models = new HashMap<>();
        models.put("大众", new String[]{"朗逸", "速腾", "迈腾", "帕萨特", "途观", "途昂"});
        models.put("丰田", new String[]{"卡罗拉", "凯美瑞", "汉兰达", "RAV4", "普拉多", "皇冠"});
        models.put("本田", new String[]{"思域", "雅阁", "CR-V", "冠道", "奥德赛", "飞度"});
        models.put("日产", new String[]{"轩逸", "天籁", "奇骏", "楼兰", "逍客", "骐达"});
        models.put("福特", new String[]{"福克斯", "蒙迪欧", "锐界", "翼虎", "探险者", "金牛座"});
        models.put("别克", new String[]{"英朗", "君威", "君越", "昂科威", "昂科拉", "GL8"});
        models.put("宝马", new String[]{"3系", "5系", "7系", "X1", "X3", "X5"});
        models.put("奔驰", new String[]{"C级", "E级", "S级", "GLA", "GLC", "GLE"});
        models.put("奥迪", new String[]{"A4L", "A6L", "A8L", "Q3", "Q5", "Q7"});
        models.put("现代", new String[]{"领动", "索纳塔", "途胜", "胜达", "ix35", "伊兰特"});
        
        // 汽车颜色
        String[] colors = {"白色", "黑色", "红色", "蓝色", "银色", "灰色", "棕色", "绿色", "黄色", "橙色"};
        
        // 汽车类型
        String[] types = {"轿车", "SUV", "MPV", "跑车", "皮卡", "新能源"};
        
        // 车辆状态
        String[] status = {"正常", "维修中", "报废", "转让中"};
        
        // 车牌前缀
        String[] licensePrefixes = {"京", "沪", "粤", "津", "冀", "晋", "蒙", "辽", "吉", "黑",
                                   "苏", "浙", "皖", "闽", "赣", "鲁", "豫", "鄂", "湘", "粤",
                                   "桂", "琼", "渝", "川", "贵", "云", "藏", "陕", "甘", "青"};
        
        int vehiclesPerOwner = count / owners.size() + 1;
        
        for (Owner owner : owners) {
            for (int i = 0; i < vehiclesPerOwner && vehicles.size() < count; i++) {
                Vehicle vehicle = new Vehicle();
                
                // 随机选择品牌
                String brand = brands[random.nextInt(brands.length)];
                
                // 根据品牌选择型号
                String[] brandModels = models.getOrDefault(brand, new String[]{"未知型号"});
                String model = brandModels[random.nextInt(brandModels.length)];
                
                // 随机选择颜色、类型和状态
                String color = colors[random.nextInt(colors.length)];
                String type = types[random.nextInt(types.length)];
                String vehicleStatus = status[random.nextInt(status.length)];
                
                // 生成车牌号
                String licensePrefix = licensePrefixes[random.nextInt(licensePrefixes.length)];
                String licenseFirstLetter = String.valueOf((char)('A' + random.nextInt(26)));
                String licenseNumbers = generateRandomDigits(5);
                String licensePlate = licensePrefix + licenseFirstLetter + licenseNumbers;
                
                // 设置车辆信息
                vehicle.setLicensePlate(licensePlate);
                vehicle.setOwner(owner);
                vehicle.setBrand(brand);
                vehicle.setModel(model);
                vehicle.setColor(color);
                vehicle.setType(type);
                vehicle.setParkingLocation("未分配");
                vehicle.setParkingPermitNumber("P" + generateRandomDigits(8));
                
                // 设置许可证到期日期，从当前日期开始的1-3年内
                Calendar permitExpiry = Calendar.getInstance();
                permitExpiry.add(Calendar.YEAR, 1 + random.nextInt(3));
                vehicle.setPermitExpiryDate(permitExpiry.getTime());
                
                vehicle.setStatus(vehicleStatus);
                vehicle.setRemarks("自动生成的测试数据");
                vehicle.setCreatedAt(new Date());
                vehicle.setUpdatedAt(new Date());
                
                vehicles.add(vehicle);
            }
        }
        
        List<Vehicle> savedVehicles = vehicleRepository.saveAll(vehicles);
        logger.info("成功生成{}条车辆数据", savedVehicles.size());
        return savedVehicles;
    }
    
    /**
     * 生成车位使用记录数据
     */
    private List<ParkingUsage> generateParkingUsages(List<Parking> parkings, List<Owner> owners, List<Vehicle> vehicles, int count) {
        logger.info("开始生成{}条车位使用记录数据", count);
        List<ParkingUsage> parkingUsages = new ArrayList<>();
        
        // 使用类型：1=租用，2=购买，3=临时
        Integer[] usageTypes = {1, 2, 3};
        
        // 支付状态
        String[] paymentStatus = {"未支付", "已支付", "部分支付", "已退款"};
        
        // 备注
        String[] remarks = {"年付车位使用费", "月付车位使用费", "季度租用", "临时停车", "长期购买", "短期租用"};
        
        // 找出空闲的车位
        List<Parking> availableParkings = parkings.stream()
                .filter(p -> "空闲".equals(p.getStatus()))
                .collect(Collectors.toList());
        
        if (availableParkings.isEmpty()) {
            logger.warn("没有可用的空闲车位，将使用所有车位");
            availableParkings = new ArrayList<>(parkings);
        }
        
        // 确保不超过可用车位数量
        int actualCount = Math.min(count, availableParkings.size());
        
        // 为每个可用车位创建使用记录
        for (int i = 0; i < actualCount; i++) {
            Parking parking = availableParkings.get(i);
            Owner owner = owners.get(random.nextInt(owners.size()));
            
            // 尝试找到属于该业主的车辆
            List<Vehicle> ownerVehicles = vehicles.stream()
                    .filter(v -> v.getOwner().getId().equals(owner.getId()))
                    .collect(Collectors.toList());
            
            Vehicle vehicle = null;
            if (!ownerVehicles.isEmpty()) {
                vehicle = ownerVehicles.get(random.nextInt(ownerVehicles.size()));
            }
            
            ParkingUsage parkingUsage = new ParkingUsage();
            parkingUsage.setParking(parking);
            parkingUsage.setOwner(owner);
            
            if (vehicle != null) {
                parkingUsage.setVehicle(vehicle);
                
                // 更新车辆的停车位置
                vehicle.setParkingLocation(parking.getName());
                vehicleRepository.save(vehicle);
            }
            
            // 设置使用类型
            Integer usageType = usageTypes[random.nextInt(usageTypes.length)];
            parkingUsage.setUsageType(usageType);
            
            // 设置开始日期为过去1年内的随机日期
            Calendar startCal = Calendar.getInstance();
            startCal.add(Calendar.YEAR, -1);
            startCal.add(Calendar.DAY_OF_YEAR, random.nextInt(365));
            Date startDate = startCal.getTime();
            parkingUsage.setStartDate(startDate);
            
            // 根据使用类型设置结束日期和费用
            Calendar endCal = Calendar.getInstance();
            endCal.setTime(startDate);
            double fee = 0.0;
            
            switch (usageType) {
                case 1: // 租用
                    endCal.add(Calendar.MONTH, 3 + random.nextInt(10)); // 3-12个月
                    int months = (endCal.get(Calendar.YEAR) - startCal.get(Calendar.YEAR)) * 12 + 
                                 (endCal.get(Calendar.MONTH) - startCal.get(Calendar.MONTH));
                    fee = parking.getPrice() * months;
                    break;
                case 2: // 购买
                    endCal.add(Calendar.YEAR, 10 + random.nextInt(21)); // 10-30年
                    fee = parking.getPrice() * 12 * 10; // 10年的租金作为购买价格
                    break;
                case 3: // 临时
                    endCal.add(Calendar.DAY_OF_YEAR, 1 + random.nextInt(30)); // 1-30天
                    int days = (int) ((endCal.getTimeInMillis() - startCal.getTimeInMillis()) / (1000 * 60 * 60 * 24));
                    fee = parking.getPrice() / 30 * days; // 按天计费
                    break;
            }
            
            parkingUsage.setEndDate(endCal.getTime());
            parkingUsage.setFee(fee);
            
            // 设置支付状态和备注
            parkingUsage.setPaymentStatus(paymentStatus[random.nextInt(paymentStatus.length)]);
            parkingUsage.setRemarks(remarks[random.nextInt(remarks.length)]);
            
            parkingUsage.setCreatedAt(new Date());
            parkingUsage.setUpdatedAt(new Date());
            
            // 更新车位状态为已使用
            parking.setStatus("已使用");
            parkingRepository.save(parking);
            
            parkingUsages.add(parkingUsage);
        }
        
        List<ParkingUsage> savedParkingUsages = parkingUsageRepository.saveAll(parkingUsages);
        logger.info("成功生成{}条车位使用记录数据", savedParkingUsages.size());
        return savedParkingUsages;
    }
    
    /**
     * 生成投诉数据
     */
    private List<Complaint> generateComplaints(List<Owner> owners, int count) {
        logger.info("开始生成{}条投诉数据", count);
        List<Complaint> complaints = new ArrayList<>();
        
        // 投诉类型
        String[] complaintTypes = {"噪音扰民", "卫生问题", "设施损坏", "安全隐患", "物业服务", "邻里纠纷", "停车问题", "装修问题", "收费问题", "其他"};
        
        // 投诉状态
        String[] complaintStatus = {"待处理", "处理中", "已解决", "已关闭", "需跟进"};
        
        // 投诉标题模板
        String[] titleTemplates = {
            "关于%s的投诉",
            "请处理%s问题",
            "%s情况严重，急需解决",
            "对%s的投诉和建议",
            "反映%s问题",
            "%s问题投诉",
            "关于%s的紧急反馈",
            "请物业重视%s",
            "%s问题亟待解决",
            "投诉：%s"
        };
        
        // 投诉内容模板
        String[] contentTemplates = {
            "我是%s的业主，最近发现%s问题非常严重，希望物业能够尽快处理。",
            "本人居住在%s，长期遭受%s困扰，多次反映无人理会，特此正式投诉。",
            "作为小区业主，我对%s问题表示强烈不满，要求物业立即解决%s。",
            "我家住在%s，最近%s问题影响了我们的正常生活，希望得到妥善解决。",
            "%s存在严重的%s问题，已经影响到我和家人的日常生活，请物业尽快处理。",
            "本人是%s的住户，关于%s问题已经持续很长时间，希望物业能够重视并解决。",
            "我居住在%s已有一段时间，一直被%s问题所困扰，希望物业部门能够认真处理。",
            "%s的%s问题已经影响到多户业主，我代表大家向物业反映，希望得到妥善解决。",
            "本人是%s的业主，强烈要求物业解决%s问题，否则将通过其他渠道投诉。",
            "我住在%s，%s问题已经持续很久，多次反映无果，特此正式投诉，希望得到重视。"
        };
        
        // 处理结果模板
        String[] resultTemplates = {
            "已安排工作人员进行处理，将于近期解决。",
            "已联系相关部门，正在协调解决中。",
            "问题已解决，感谢您的反馈。",
            "经核实，情况属实，已采取相应措施。",
            "已安排专人负责，将持续跟进直至问题解决。",
            "已记录您的投诉，将按流程处理。",
            "正在调查核实中，将尽快给您回复。",
            "已解决，如有后续问题请再次反馈。",
            "问题较为复杂，需要一定时间处理，请耐心等待。",
            "已转交相关责任部门处理，将督促其尽快解决。"
        };
        
        // 生成随机的投诉地点
        String[] locations = {"小区公共区域", "电梯", "楼道", "地下车库", "花园", "健身区", "游泳池", "垃圾房", "门禁系统", "安保室"};
        
        int complaintsPerOwner = count / owners.size() + 1;
        
        for (Owner owner : owners) {
            for (int i = 0; i < complaintsPerOwner && complaints.size() < count; i++) {
                Complaint complaint = new Complaint();
                
                // 随机选择投诉类型和状态
                String complaintType = complaintTypes[random.nextInt(complaintTypes.length)];
                String status = complaintStatus[random.nextInt(complaintStatus.length)];
                
                // 随机选择地点
                String location = locations[random.nextInt(locations.length)];
                
                // 生成标题和内容
                String titleTemplate = titleTemplates[random.nextInt(titleTemplates.length)];
                String contentTemplate = contentTemplates[random.nextInt(contentTemplates.length)];
                
                String title = String.format(titleTemplate, complaintType);
                String content = String.format(contentTemplate, location, complaintType);
                
                // 设置投诉信息
                complaint.setOwner(owner);
                complaint.setTitle(title);
                complaint.setContent(content);
                complaint.setType(complaintType);
                complaint.setStatus(status);
                
                // 设置投诉时间为过去3个月内的随机时间
                Calendar complainDate = Calendar.getInstance();
                complainDate.add(Calendar.MONTH, -3);
                complainDate.add(Calendar.DAY_OF_YEAR, random.nextInt(90));
                complaint.setSubmitTime(complainDate.getTime());
                
                // 如果状态不是"待处理"，则添加处理结果和处理时间
                if (!"待处理".equals(status)) {
                    String resultTemplate = resultTemplates[random.nextInt(resultTemplates.length)];
                    complaint.setResult(resultTemplate);
                    
                    // 处理时间在投诉时间之后的1-14天
                    Calendar processDate = Calendar.getInstance();
                    processDate.setTime(complainDate.getTime());
                    processDate.add(Calendar.DAY_OF_YEAR, 1 + random.nextInt(14));
                    complaint.setHandleTime(processDate.getTime());
                }
                
                complaint.setCreatedAt(new Date());
                complaint.setUpdatedAt(new Date());
                
                complaints.add(complaint);
            }
        }
        
        List<Complaint> savedComplaints = complaintRepository.saveAll(complaints);
        logger.info("成功生成{}条投诉数据", savedComplaints.size());
        return savedComplaints;
    }
    
    /**
     * 生成报修数据
     */
    private List<Repair> generateRepairs(List<Owner> owners, List<Home> homes, int count) {
        logger.info("开始生成{}条报修数据", count);
        List<Repair> repairs = new ArrayList<>();
        
        // 报修类型
        String[] repairTypes = {"水电维修", "暖气维修", "门窗维修", "墙面维修", "地板维修", "家具维修", "电器维修", "管道疏通", "公共设施", "其他"};
        
        // 报修状态
        String[] repairStatus = {"待处理", "已派单", "维修中", "已完成", "已取消", "需复检"};
        
        // 报修标题模板
        String[] titleTemplates = {
            "%s报修申请",
            "请安排%s维修",
            "%s故障报修",
            "关于%s的维修申请",
            "%s问题请求维修",
            "紧急：%s需要维修",
            "%s维修需求",
            "申请维修%s",
            "%s损坏报修",
            "请尽快处理%s问题"
        };
        
        // 报修内容模板
        String[] contentTemplates = {
            "我家%s出现%s问题，请尽快安排维修人员处理。",
            "本人居住在%s，%s出现故障，影响正常使用，请安排维修。",
            "%s的%s已经损坏，需要专业人员来维修，谢谢。",
            "我是%s的住户，%s出现问题，具体表现为：无法正常使用，请尽快处理。",
            "%s内的%s出现漏水/破损/故障，请物业安排人员检修。",
            "本人是%s的业主，%s已经使用多年，现在出现问题，请安排维修。",
            "我家%s的%s最近出现异常，可能需要更换零部件，请安排专业人员查看。",
            "%s内%s出现严重问题，已经影响到日常生活，请尽快安排人员维修。",
            "报修%s的%s，问题描述：无法正常工作，请尽快处理。",
            "我住在%s，%s已经损坏一段时间了，希望能尽快安排人员来修理。"
        };
        
        // 处理结果模板
        String[] resultTemplates = {
            "已完成维修，问题已解决。",
            "已更换损坏部件，恢复正常使用。",
            "经检查，问题已修复，请业主验收。",
            "维修人员已处理完毕，如有问题请再次报修。",
            "已完成维修工作，并进行了功能测试，运行正常。",
            "已修复故障，并对相关设施进行了保养。",
            "问题已解决，建议定期检查维护。",
            "维修完成，已恢复正常使用功能。",
            "已处理完毕，并向业主说明了正确使用方法。",
            "维修工作已完成，已与业主确认问题解决。"
        };
        
        // 生成随机的报修位置
        String[] locations = {"客厅", "卧室", "厨房", "卫生间", "阳台", "走廊", "入户门", "窗户", "天花板", "地板"};
        
        int repairsPerOwner = count / owners.size() + 1;
        
        for (Owner owner : owners) {
            // 找出属于该业主的房屋
            List<Home> ownerHomes = homes.stream()
                    .filter(h -> h.getOwner() != null && h.getOwner().getId().equals(owner.getId()))
                    .collect(Collectors.toList());
            
            // 如果该业主没有房屋，则跳过
            if (ownerHomes.isEmpty()) {
                continue;
            }
            
            for (int i = 0; i < repairsPerOwner && repairs.size() < count; i++) {
                Repair repair = new Repair();
                
                // 随机选择一个属于该业主的房屋
                Home home = ownerHomes.get(random.nextInt(ownerHomes.size()));
                
                // 随机选择报修类型和状态
                String repairType = repairTypes[random.nextInt(repairTypes.length)];
                String status = repairStatus[random.nextInt(repairStatus.length)];
                
                // 随机选择位置
                String location = locations[random.nextInt(locations.length)];
                
                // 生成标题和内容
                String titleTemplate = titleTemplates[random.nextInt(titleTemplates.length)];
                String contentTemplate = contentTemplates[random.nextInt(contentTemplates.length)];
                
                String title = String.format(titleTemplate, repairType);
                String content = String.format(contentTemplate, home.getName(), repairType);
                
                // 设置报修信息
                repair.setOwner(owner);
                repair.setHome(home);
                repair.setDescription(content);
                repair.setType(repairType);
                repair.setStatus(status);
                
                // 设置报修时间为过去2个月内的随机时间
                Calendar repairDate = Calendar.getInstance();
                repairDate.add(Calendar.MONTH, -2);
                repairDate.add(Calendar.DAY_OF_YEAR, random.nextInt(60));
                repair.setReportTime(repairDate.getTime());
                
                // 如果状态不是"待处理"或"已派单"，则添加处理结果和处理时间
                if (!("待处理".equals(status) || "已派单".equals(status))) {
                    String resultTemplate = resultTemplates[random.nextInt(resultTemplates.length)];
                    repair.setResult(resultTemplate);
                    
                    // 处理时间在报修时间之后的1-7天
                    Calendar processDate = Calendar.getInstance();
                    processDate.setTime(repairDate.getTime());
                    processDate.add(Calendar.DAY_OF_YEAR, 1 + random.nextInt(7));
                    repair.setHandleTime(processDate.getTime());
                }
                
                repair.setCreatedAt(new Date());
                repair.setUpdatedAt(new Date());
                
                repairs.add(repair);
            }
        }
        
        List<Repair> savedRepairs = repairRepository.saveAll(repairs);
        logger.info("成功生成{}条报修数据", savedRepairs.size());
        return savedRepairs;
    }
    
    /**
     * 生成活动数据
     */
    private List<Activity> generateActivities(List<Community> communities, int count) {
        logger.info("开始生成{}条活动数据", count);
        List<Activity> activities = new ArrayList<>();
        
        // 活动类型
        String[] activityTypes = {"文化活动", "体育活动", "亲子活动", "节日庆祝", "公益活动", "健康讲座", "社区会议", "才艺展示", "环保活动", "安全教育"};
        
        // 活动状态
        String[] activityStatus = {"未开始", "报名中", "进行中", "已结束", "已取消"};
        
        // 活动标题模板
        String[] titleTemplates = {
            "社区%s活动",
            "%s嘉年华",
            "%s专题活动",
            "欢乐%s节",
            "%s体验日",
            "%s交流会",
            "趣味%s大赛",
            "%s知识讲座",
            "%s主题活动",
            "社区%s日"
        };
        
        // 活动内容模板
        String[] contentTemplates = {
            "为丰富社区居民的文化生活，增进邻里关系，特举办此次%s活动，欢迎广大业主参与。",
            "本次%s活动旨在促进社区和谐，提升居民幸福感，活动内容丰富多彩，包括%s等环节。",
            "为营造良好的社区氛围，提高居民参与度，特举办%s活动，活动将在%s举行。",
            "本次%s活动由社区居委会主办，物业公司协办，旨在为居民提供一个展示才艺、增进交流的平台。",
            "为弘扬中华传统文化，增强社区凝聚力，特举办此次%s活动，活动形式多样，内容丰富。",
            "本次%s活动面向全体业主，无需报名费用，请有兴趣的居民提前报名参加。",
            "为提高居民的生活质量和健康水平，特邀请专业人士举办%s活动，欢迎大家踊跃参与。",
            "本次%s活动将为居民提供一个相互了解、增进友谊的机会，活动设有精美礼品和抽奖环节。",
            "为创建和谐社区，增强社区凝聚力，特举办%s活动，活动时间为%s，地点在%s。",
            "本次%s活动是我社区的传统活动，每年举办一次，深受居民喜爱，欢迎新老业主共同参与。"
        };
        
        // 活动地点
        String[] locations = {"社区活动中心", "小区广场", "社区会议室", "小区花园", "社区图书馆", "社区健身房", "小区篮球场", "社区多功能厅", "小区游泳池", "社区舞蹈室"};
        
        // 活动组织者
        String[] organizers = {"社区居委会", "物业管理处", "业主委员会", "社区志愿者协会", "社区文化中心", "社区老年协会", "社区青年志愿者", "社区妇女联合会", "社区环保小组", "社区安全委员会"};
        
        int activitiesPerCommunity = count / communities.size() + 1;
        
        for (Community community : communities) {
            for (int i = 0; i < activitiesPerCommunity && activities.size() < count; i++) {
                Activity activity = new Activity();
                
                // 随机选择活动类型和状态
                String activityType = activityTypes[random.nextInt(activityTypes.length)];
                String status = activityStatus[random.nextInt(activityStatus.length)];
                
                // 随机选择地点和组织者
                String location = locations[random.nextInt(locations.length)];
                String organizer = organizers[random.nextInt(organizers.length)];
                
                // 生成标题和内容
                String titleTemplate = titleTemplates[random.nextInt(titleTemplates.length)];
                String contentTemplate = contentTemplates[random.nextInt(contentTemplates.length)];
                
                String title = String.format(titleTemplate, activityType);
                String content = String.format(contentTemplate, activityType, location, community.getName());
                
                // 设置活动开始时间，根据状态确定
                Calendar startCal = Calendar.getInstance();
                Calendar endCal = Calendar.getInstance();
                
                switch (status) {
                    case "未开始":
                        // 未来1-30天内开始
                        startCal.add(Calendar.DAY_OF_YEAR, 1 + random.nextInt(30));
                        break;
                    case "报名中":
                        // 未来1-14天内开始
                        startCal.add(Calendar.DAY_OF_YEAR, 1 + random.nextInt(14));
                        break;
                    case "进行中":
                        // 过去0-3天开始，未来1-7天结束
                        startCal.add(Calendar.DAY_OF_YEAR, -random.nextInt(4));
                        break;
                    case "已结束":
                    case "已取消":
                        // 过去1-60天开始，过去1-30天结束
                        startCal.add(Calendar.DAY_OF_YEAR, -(1 + random.nextInt(60)));
                        break;
                }
                
                // 设置活动结束时间，活动持续1-8小时
                endCal.setTime(startCal.getTime());
                endCal.add(Calendar.HOUR_OF_DAY, 1 + random.nextInt(8));
                
                // 设置活动信息
                activity.setTitle(title);
                activity.setContent(content);
                activity.setCommunity(community);
                activity.setLocation(location);
                activity.setStartTime(startCal.getTime());
                activity.setEndTime(endCal.getTime());
                activity.setOrganizer(organizer);
                activity.setStatus(status);
                activity.setCreatedAt(new Date());
                activity.setUpdatedAt(new Date());
                
                activities.add(activity);
            }
        }
        
        List<Activity> savedActivities = activityRepository.saveAll(activities);
        logger.info("成功生成{}条活动数据", savedActivities.size());
        return savedActivities;
    }
    
    /**
     * 生成信箱数据
     */
    private List<Mailbox> generateMailboxes(List<Owner> owners, int count) {
        logger.info("开始生成{}条信箱数据", count);
        List<Mailbox> mailboxes = new ArrayList<>();
        
        // 信箱类型
        String[] mailboxTypes = {"建议", "投诉", "表扬", "咨询", "其他"};
        
        // 信箱状态
        String[] mailboxStatus = {"未读", "已读", "已回复", "已关闭", "已转交"};
        
        // 信箱标题模板
        String[] titleTemplates = {
            "关于%s的%s",
            "%s方面的%s",
            "对%s的%s",
            "%s问题%s",
            "关于%s的%s和建议",
            "%s相关%s",
            "%s方面需要%s",
            "希望%s能够%s",
            "%s的%s情况",
            "请%s关注%s问题"
        };
        
        // 信箱内容模板
        String[] contentTemplates = {
            "我是小区业主，对%s有一些%s，希望物业能够重视并解决。",
            "作为业主，我想对%s提出一些%s，希望能得到妥善处理。",
            "我居住在小区已有一段时间，对%s有一些%s，希望能引起重视。",
            "本人是小区业主，关于%s有一些%s，请物业部门尽快处理。",
            "我想对%s提出%s，希望能够得到及时回复。",
            "作为长期居住在小区的业主，我对%s有一些%s，希望能够改进。",
            "我对小区的%s有一些%s，希望物业能够认真考虑。",
            "关于%s，我有一些%s，希望能够引起相关部门的重视。",
            "我想就%s问题提出%s，希望能够得到妥善解决。",
            "对于小区的%s，我有一些%s，希望能够得到改善。"
        };
        
        // 回复模板
        String[] replyTemplates = {
            "感谢您的反馈，我们已收到您关于%s的%s，将尽快处理。",
            "您好，关于您提出的%s问题，我们已安排专人处理，请耐心等待。",
            "您的%s已收到，我们会认真考虑您的%s，并尽快给您回复。",
            "感谢您对小区工作的关注，我们已记录您关于%s的%s，将积极改进。",
            "您好，我们已收到您对%s的%s，正在处理中，请您耐心等待。",
            "关于您提出的%s问题，我们已经开始着手解决，感谢您的%s。",
            "您的%s我们已经收到，针对您提出的%s，我们将尽快处理并回复。",
            "感谢您的%s，关于%s问题，我们会认真对待并尽快解决。",
            "您好，您关于%s的%s我们已收到，将按照流程进行处理。",
            "我们已经注意到您提出的关于%s的%s，将尽快处理并给您答复。"
        };
        
        // 主题内容
        String[] subjects = {"物业服务", "安全管理", "环境卫生", "设施维护", "收费标准", "停车管理", "噪音问题", "邻里关系", "装修管理", "公共设施"};
        
        // 反馈类型
        String[] feedbackTypes = {"建议", "意见", "投诉", "表扬", "疑问", "要求", "反馈", "询问", "提议", "困扰"};
        
        int mailboxesPerOwner = count / owners.size() + 1;
        
        for (Owner owner : owners) {
            for (int i = 0; i < mailboxesPerOwner && mailboxes.size() < count; i++) {
                Mailbox mailbox = new Mailbox();
                
                // 随机选择信箱类型和状态
                String mailboxType = mailboxTypes[random.nextInt(mailboxTypes.length)];
                String status = mailboxStatus[random.nextInt(mailboxStatus.length)];
                
                // 随机选择主题和反馈类型
                String subject = subjects[random.nextInt(subjects.length)];
                String feedbackType = feedbackTypes[random.nextInt(feedbackTypes.length)];
                
                // 生成标题和内容
                String titleTemplate = titleTemplates[random.nextInt(titleTemplates.length)];
                String contentTemplate = contentTemplates[random.nextInt(contentTemplates.length)];
                
                String title = String.format(titleTemplate, subject, feedbackType);
                String content = String.format(contentTemplate, subject, feedbackType);
                
                // 设置信箱基本信息
                mailbox.setOwner(owner);
                mailbox.setTitle(title);
                mailbox.setContent(content);
                mailbox.setType(mailboxType);
                mailbox.setStatus(status);
                
                // 设置发送时间为过去3个月内的随机时间
                Calendar sendDate = Calendar.getInstance();
                sendDate.add(Calendar.MONTH, -3);
                sendDate.add(Calendar.DAY_OF_YEAR, random.nextInt(90));
                mailbox.setSubmitTime(sendDate.getTime());
                
                // 如果状态不是"未读"，则添加回复内容和回复时间
                if (!"未读".equals(status)) {
                    String replyTemplate = replyTemplates[random.nextInt(replyTemplates.length)];
                    String reply = String.format(replyTemplate, subject, feedbackType);
                    mailbox.setReplyContent(reply);
                    
                    // 回复时间在发送时间之后的1-7天
                    Calendar replyDate = Calendar.getInstance();
                    replyDate.setTime(sendDate.getTime());
                    replyDate.add(Calendar.DAY_OF_YEAR, 1 + random.nextInt(7));
                    mailbox.setReplyTime(replyDate.getTime());
                }
                
                mailbox.setCreatedAt(new Date());
                mailbox.setUpdatedAt(new Date());
                
                mailboxes.add(mailbox);
            }
        }
        
        List<Mailbox> savedMailboxes = mailboxRepository.saveAll(mailboxes);
        logger.info("成功生成{}条信箱数据", savedMailboxes.size());
        return savedMailboxes;
    }
} 